package com.dongdong.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdong.vo.ItemVO;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class ESUtil {

    private RestHighLevelClient client;

    /**
     * 根据索引名以及ID查询数据
     * @param index 索引名称
     * @param id    数据ＩＤ
     * @return
     */
    public String getDocument(String index, String id){
        GetResponse getResponse = null;
        try{
            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9201, "http")));

            GetRequest getRequest = new GetRequest(index,"_doc", id );
            getResponse = client.get(getRequest, RequestOptions.DEFAULT);
            System.out.println(JSONObject.toJSONString(getResponse));
            client.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        return JSONObject.toJSONString(getResponse);
    }

    /**
     * 分页查询索引所有数据
     * @param index
     * @param current
     * @param size
     * @return
     * @throws IOException
     */
    public String searchAll(String index, int current, int size) throws IOException {
        client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9201, "http")));
        SearchRequest searchRequest = new SearchRequest(index);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchSourceBuilder.from(current);
        searchSourceBuilder.size(size);

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSONString(searchResponse));
        //处理返回结果
        SearchHits hits = searchResponse.getHits();
        client.close();
        return JSONObject.toJSONString(hits);
    }

    private List<Map<String, Object>> dealResult(SearchHits hits){
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (SearchHit hit : hits.getHits()) {
            Map<String, Object> map = hit.getSourceAsMap();
            result.add(map);
        }
        return result;
    }


    /*高亮查询索引以及数据*/
    public String keywordSearch(String index, String value,
                                int current, int size){
        List<Map<String, Object>> result = null;
        try{
            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9201, "http")));
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index);

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //支持全词搜索的字段有：keywordName，keywordAuthor"
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(value, "title"));//是要包含这个字段都会添加到highl..中  看下边
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //高亮字段
            highlightBuilder.field("title").requireFieldMatch(false);
            searchSourceBuilder.from(current);
            searchSourceBuilder.size(size);
            searchSourceBuilder.highlighter(highlightBuilder);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println(searchResponse);
            //处理返回结果
            result = dealResult(searchResponse.getHits());
            //解析响应
            SearchHits searchHits = searchResponse.getHits();//接收到结果之后进行响应
            //获取总条数
//            long total = searchHits.getTotalHits().value;
//            System.out.println("共搜索到" + total + "条数据");
            //文档数组
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {//将获取到的所有数据  循环遍历
                String json = hit.getSourceAsString();
                //反序列化
                ItemVO itemVO = JSON.parseObject(json, ItemVO.class);
                //获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                //根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("title");//高亮
                //获取高亮值
                String title = highlightField.getFragments()[0].string();//<em></em>   貌似有一个em标签
                itemVO.setTitle(title);
                System.out.println("itemVO = " + itemVO);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return JSONObject.toJSONString(result);//转成json字符串  进行返回
    }
}